<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-form :inline="true" :model="queryParams" v-show="showSearch">
      <el-form-item label="标题">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="上线" :value="1" />
          <el-option label="下线" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="openAddDialog"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="hotVideoList" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? "上线" : "下线" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="agentId" label="关联智能体" />
      <el-table-column prop="coverUrl" label="封面地址">
        <template #default="{ row }">
          <a
            v-if="row.coverUrl"
            href="javascript:void(0);"
            @click="openImage(row.coverUrl)"
            style="color: #409eff">
            查看封面
          </a>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column prop="videoUrl" label="视频地址">
        <template #default="{ row }">
          <a
            v-if="row.videoUrl"
            :href="row.videoUrl"
            target="_blank"
            style="color: #67c23a"
            >查看视频</a
          >
          <span v-else>—</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
   <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增热门视频" width="600px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="视频标题" required>
          <el-input v-model="addForm.title" placeholder="请输入视频标题" />
        </el-form-item>

        <!-- 封面上传 -->
        <el-form-item label="封面图" required>
          <el-upload
            ref="coverUploader"
            class="upload-cover"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleCoverSuccess"
            :before-upload="beforeImageUpload"
            :show-file-list="true"
            list-type="picture-card"
            accept="image/*"
          >
            <template #default>
              <i class="el-icon-plus"></i>
            </template>
          </el-upload>
          <template v-if="addForm.coverUrl">
            <img
              :src="addForm.coverUrl"
              style="width: 100px; height: 100px; margin-left: 10px; border-radius: 8px"
            />
          </template>
        </el-form-item>

        <!-- 视频上传 -->
        <el-form-item label="视频文件" required>
          <el-upload
            ref="videoUploader"
            class="upload-video"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload"
            :show-file-list="true"
            accept="video/*"
            list-type="text"
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 mp4、mov、avi 格式，最大 500MB
              </div>
            </template>
          </el-upload>
          <video
            v-if="addForm.videoUrl"
            :src="addForm.videoUrl"
            controls
            style="width: 100%; margin-top: 10px; border-radius: 8px"
          ></video>
        </el-form-item>

        <!-- 关联智能体 -->
        <el-form-item label="关联智能体" required>
          <el-select
            v-model="addForm.agentId"
            placeholder="请选择智能体"
            filterable
          >
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" required>
          <el-radio-group v-model="addForm.status">
            <el-radio :label="1">上线</el-radio>
            <el-radio :label="0">下线</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序">
          <el-input-number v-model="addForm.sort" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </template>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改热门视频" width="600px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="视频标题" required>
          <el-input v-model="editForm.title" placeholder="请输入视频标题" />
        </el-form-item>

        <!-- 封面上传 -->
        <el-form-item label="封面图" required>
          <el-upload
            class="upload-cover"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleEditCoverSuccess"
            :before-upload="beforeImageUpload"
            :show-file-list="true"
            list-type="picture-card"
            accept="image/*"
          >
            <template #default>
              <i class="el-icon-plus"></i>
            </template>
          </el-upload>
          <template v-if="editForm.coverUrl">
            <img
              :src="editForm.coverUrl"
              style="width: 100px; height: 100px; margin-left: 10px; border-radius: 8px"
            />
          </template>
        </el-form-item>

        <!-- 视频上传 -->
        <el-form-item label="视频文件" required>
          <el-upload
            class="upload-video"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleEditVideoSuccess"
            :before-upload="beforeVideoUpload"
            :show-file-list="true"
            accept="video/*"
            list-type="text"
          >
            <el-button type="primary">上传视频</el-button>
          </el-upload>
          <video
            v-if="editForm.videoUrl"
            :src="editForm.videoUrl"
            controls
            style="width: 100%; margin-top: 10px; border-radius: 8px"
          ></video>
        </el-form-item>

        <el-form-item label="关联智能体" required>
          <el-select
            v-model="editForm.agentId"
            placeholder="请选择智能体"
            filterable
          >
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" required>
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">上线</el-radio>
            <el-radio :label="0">下线</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序">
          <el-input-number v-model="editForm.sort" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { listHotVideo, addHotVideo, listAIAgent, updateHotVideo } from "@/api/min-app/hotvideo";
import { getToken } from "@/utils/auth";

// ----------------------- 基础数据 -----------------------
const hotVideoList = ref([]);
const total = ref(0);
const loading = ref(false);
const showSearch = ref(true);
const agentList = ref([]);

const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

const addForm = ref({
  agentId: null,
  coverUrl: "",
  sort: 0,
  status: 1,
  title: "",
  videoUrl: "",
});

const editForm = ref({
  id: null,
  agentId: null,
  coverUrl: "",
  sort: 0,
  status: 1,
  title: "",
  videoUrl: "",
});

// ----------------------- 上传配置 -----------------------
const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/admin/hotvideo/upload`;
const uploadHeaders = { 'Authorization-Admin': getToken() };

function beforeImageUpload(file) {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (file.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
}

function beforeVideoUpload(file) {
  const isVideo = file.type.startsWith("video/");
  if (!isVideo) {
    ElMessage.error("只能上传视频文件!");
    return false;
  }
  if (file.size / 1024 / 1024 > 500) {
    ElMessage.error("视频大小不能超过 500MB!");
    return false;
  }
  return true;
}

const openImage = (url) => {
  window.open(url, '_blank', 'noopener,noreferrer');
};

function handleCoverSuccess(res) {
  if (res.code === 200 || res.code === 0) {
    addForm.value.coverUrl = res.url || res.data?.url;
    ElMessage.success("封面上传成功");
  } else {
    ElMessage.error(res.msg || "封面上传失败");
  }
}

function handleVideoSuccess(res) {
  if (res.code === 200 || res.code === 0) {
    addForm.value.videoUrl = res.url || res.data?.url;
    ElMessage.success("视频上传成功");
  } else {
    ElMessage.error(res.msg || "视频上传失败");
  }
}

function handleEditCoverSuccess(res) {
  if (res.code === 200 || res.code === 0) {
    editForm.value.coverUrl = res.url || res.data?.url;
    ElMessage.success("封面上传成功");
  } else {
    ElMessage.error(res.msg || "封面上传失败");
  }
}

function handleEditVideoSuccess(res) {
  if (res.code === 200 || res.code === 0) {
    editForm.value.videoUrl = res.url || res.data?.url;
    ElMessage.success("视频上传成功");
  } else {
    ElMessage.error(res.msg || "视频上传失败");
  }
}

// ----------------------- 新增 -----------------------
async function submitAdd() {
  const { title, agentId, coverUrl, videoUrl } = addForm.value;
  if (!title || !agentId || !coverUrl || !videoUrl) {
    ElMessage.warning("请填写完整信息并上传文件");
    return;
  }

  try {
    const res = await addHotVideo(addForm.value);
    if (res.code === 200 || res.code === 0) {
      ElMessage.success("新增成功");
      addDialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || "新增失败");
    }
  } catch {
    ElMessage.error("请求异常，请检查网络或接口");
  }
}

// ----------------------- 修改 -----------------------
function handleUpdate(row) {
  editForm.value = { ...row };
  getAgentList();
  editDialogVisible.value = true;
}

async function submitEdit() {
  const { id, title, agentId, coverUrl, videoUrl } = editForm.value;
  if (!id || !title || !agentId || !coverUrl || !videoUrl) {
    ElMessage.warning("请填写完整信息并上传文件");
    return;
  }

  try {
    const res = await updateHotVideo(editForm.value);
    if (res.code === 200 || res.code === 0) {
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || "修改失败");
    }
  } catch {
    ElMessage.error("请求异常，请检查网络或接口");
  }
}

// ----------------------- 数据 -----------------------
function openAddDialog() {
  addForm.value = {
    agentId: null,
    coverUrl: "",
    sort: 0,
    status: 1,
    title: "",
    videoUrl: "",
  };
  addDialogVisible.value = true;
  getAgentList();
}

function getAgentList() {
  listAIAgent({
    page: 1,
    size: 999,
    agentType: -1,
    isActive: 0,
  }).then((res) => {
    agentList.value = res.data?.records || [];
  });
}

const queryParams = ref({
  page: 1,
  size: 10,
  title: "",
  status: null,
});

function getList() {
  loading.value = true;
  listHotVideo(queryParams.value)
    .then((res) => {
      hotVideoList.value = res.rows || res.data?.records || [];
      total.value = Number(res.total || res.data?.total || 0);
    })
    .finally(() => (loading.value = false));
}

function resetQuery() {
  queryParams.value = {
    page: 1,
    size: 10,
    title: "",
    status: null,
  };
  getList();
}

getList();
</script>

<style scoped>
.upload-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
